package com.dp.service.impl;

import java.io.Serializable;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityNotFoundException;
import javax.persistence.NoResultException;
import javax.persistence.NonUniqueResultException;
import javax.persistence.Query;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dp.pojo.Weather;
import com.dp.pub.SysProperty;
import com.dp.service.impl3.BaseImpl;
import com.dp.util.DataMap;
import com.dp.vo.NewsButtons;
import com.dp.vo.NewsResources;

@Service
@Transactional
public class WeatherServiceImpl extends BaseImpl {

	@SuppressWarnings("unchecked")
	public List findWeatherButton() {
		List obj =null;
		try {
		String hql = "SELECT nb FROM NewsButtons nb where nb.buttontype=4 ";

		Query query = em.createQuery(hql);
		 	obj = query.getResultList();
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (obj == null) {
			return null;
		} else {
			return obj;
		}
	}

	public void save(NewsButtons button) {
		try {
		if (button.getButtonid() == null) {
			// new
			em.persist(button);
		} else {
			// update
			em.merge(button);
		}
		em.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void remove(int id) {
		try {
		NewsButtons button = find(id);
		if (button != null) {
			em.remove(button);
		}
		em.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public NewsButtons find(int id) {
		NewsButtons button=null;
		try {
			button= em.find(NewsButtons.class, id);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return button;

	}
	
	//********************************************手动录入天气预报_Start*******************************************************
	public int findAllWeatherEntityCount(DataMap hashMap){
		Weather weather=(Weather)hashMap.get("weather");
		int iCount = 0; 
		try {
		//	this.init();
			this.sql="SELECT count(nb.buttonid) FROM news_buttons nb join t_weatherdetail tw on nb.buttonname=tw.province WHERE nb.buttontype=4 and tw.weatherdate in('0','1','2')";
			if(weather!=null){
				if(weather.getButtonid()!=null&& weather.getButtonid().toString().trim().length() > 0){
					sql+=" AND nb.buttonid='"+ weather.getButtonid().toString().trim() + "'";
				}
				if(weather.getProvince()!=null&& weather.getProvince().toString().trim().length() > 0){
					sql+=" AND tw.province like '%"+ weather.getProvince().toString().trim() + "%'";
				}
				if(weather.getWeather_phenomena()!=null&& weather.getWeather_phenomena().toString().trim().length() > 0){
					sql+=" AND tw.weatherinfo like '% %"+ weather.getWeather_phenomena().toString().trim() + "% %'";
				}
				if(weather.getWeathericon()!=null&& weather.getWeathericon().toString().trim().length() > 0){
					sql+=" AND tw.weathericon='"+ weather.getWeathericon().toString().trim() + "'";
				}
				if(weather.getData_status()!=null&& weather.getData_status().toString().trim().length() > 0){
					if("0".equals(weather.getData_status())){
						//有效
						sql+=" AND updatetime > '"+new SimpleDateFormat("yyyy-MM-dd").format(new java.util.Date()) + "'";
					}else if("1".equals(weather.getData_status())){
						//已过期
						sql+=" AND updatetime < '" +new SimpleDateFormat("yyyy-MM-dd").format(new java.util.Date()) + "'";
					}
				}
			}
			
			iCount=this.getOneInt();
		} catch (Exception e) {
			logger.info("findAllWeatherEntityCount fail !!!" + e.getMessage());
			e.printStackTrace();
		} 
		return iCount;
	}
	
	/**
	 * Find all the Weather Entity
	 * @param hashMap
	 * @return List<Weather>
	 */
	public List<Weather> findAllWeatherEntity(DataMap hashMap){
		List<Weather> weatherList=null;
		Integer firstrow=(Integer)hashMap.get("firstrow");
		Integer maxrow=(Integer)hashMap.get("maxrow");
		Weather weather=(Weather)hashMap.get("weather");
		try {
		
			this.sql="SELECT nb.buttonid,tw.province,tw.weatherdate,tw.weatherinfo,tw.weatherindex,tw.weathericon,tw.updatetime FROM news_buttons nb join t_weatherdetail tw on nb.buttonname=tw.province WHERE nb.buttontype=4 and tw.weatherdate in('0','1','2')";
			if(weather!=null){
				if(weather.getButtonid()!=null&& weather.getButtonid().toString().trim().length() > 0){
					sql+=" AND nb.buttonid='"+ weather.getButtonid().toString().trim() + "'";
				}
				if(weather.getProvince()!=null&& weather.getProvince().toString().trim().length() > 0){
					sql+=" AND tw.province like '%"+ weather.getProvince().toString().trim() + "%'";
				}
				if(weather.getWeather_phenomena()!=null&& weather.getWeather_phenomena().toString().trim().length() > 0){
					sql+=" AND tw.weatherinfo like '% %"+ weather.getWeather_phenomena().toString().trim() + "% %'";
				}
				if(weather.getWeathericon()!=null&& weather.getWeathericon().toString().trim().length() > 0){
					sql+=" AND tw.weathericon='"+ weather.getWeathericon().toString().trim() + "'";
				}
				if(weather.getData_status()!=null&& weather.getData_status().toString().trim().length() > 0){
					if("0".equals(weather.getData_status())){
						//有效
						sql+=" AND updatetime > '"+new SimpleDateFormat("yyyy-MM-dd").format(new java.util.Date()) + "'";
					}else if("1".equals(weather.getData_status())){
						//已过期
						sql+=" AND updatetime < '" +new SimpleDateFormat("yyyy-MM-dd").format(new java.util.Date()) + "'";
					}
				}
			}
			sql+=" group by province,weatherdate ";
			if(firstrow!=null&&maxrow!=null){
				sql+=" limit "+firstrow+","+maxrow;
			}
		
			weatherList=new ArrayList<Weather>();
			Weather weather_temp=null;
			SimpleDateFormat fmt_temp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			List<Object[]> tempp=this.em.createNativeQuery(sql).getResultList();
			for(Object[]o:tempp)
			{
				weather_temp=new Weather();
				weather_temp.setButtonid(this.getInteger(o[0]));
				weather_temp.setProvince(this.getString(o[1]));
				weather_temp.setWeatherdate(this.getString(o[2]));
				weather_temp.setWeatherinfo(this.getString(o[3]));
				weather_temp.setWeatherindex(this.getString(o[4]));
				weather_temp.setWeathericon(this.getInteger(o[5]));
				weather_temp.setUpdatetime(fmt_temp.parse(this.getString(o[6])));
				weatherList.add(weather_temp);
			}
		} catch (Exception e) {
			logger.info("findAllWeatherEntity fail !!!" + e.getMessage());
			e.printStackTrace();
		}
		return weatherList;
	}
	
	
	public Object getSingleResult(Query query) {
		Object o =null;
		try {
			o = query.getSingleResult();
		} catch (NoResultException ex) {
			return null;
		} catch (NonUniqueResultException ex) {
			o = query.getResultList();
			return ((List) o).get(0);
		}
		return o;
	}
	
	/**
	 * 得到图标列表
	 * @return	List<NewsResources>
	 */
	@Transactional(readOnly = true)
	public List<NewsResources> getIconList() {
		List<NewsResources> queryList=null;
		try {
			//concat(rid,'|',fullpath)
			StringBuffer sf = new StringBuffer("SELECT n FROM NewsResources n WHERE isusebysys=1 AND resourcetype=1 AND (rid between :startindex AND :startindex+10)");
			Query query = em.createQuery(sf.toString());
			int startindex=127;
			try {
				if(SysProperty.getPrep("sysweathericon_startindex_value")!=null&&!"".equals(SysProperty.getPrep("sysweathericon_startindex_value"))){
					startindex=Integer.parseInt(SysProperty.getPrep("sysweathericon_startindex_value")); 
				}
			} catch (NumberFormatException e) {
				e.printStackTrace();
			}
			query.setParameter("startindex", startindex);
			queryList = query.getResultList();
			if(queryList!=null){
				String uploadroot = SysProperty.getPrep("video-uploadpath");
				if(uploadroot == null || uploadroot.equals(""))
					uploadroot = SysProperty.getPrep("uploadpath");
				for(NewsResources nr:queryList){
					nr.setFullpath(nr.getFullpath().replace(uploadroot,""));
				}
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
			e.printStackTrace();
		}
		return queryList;
	}
	
	/**
	 * 新增天气预报
	 * @param hashMap weatherButton,weatherDetailList
	 * @return	int -2:记录存在;-1：失败;0:成功;
	 */
	public int addWeather(DataMap hashMap){
		List<Weather> weatherList=(List<Weather>) hashMap.get("weatherList");
		NewsButtons weatherButton=(NewsButtons) hashMap.get("weatherButton");
		int resultInt = 0;
		try {
			//this.init();
			this.sql="SELECT count(*) FROM news_buttons WHERE buttonname='"+weatherButton.getButtonname()+"' AND buttontype=4";
			
			if(this.getOneInt()>0){
				return -2;
			}
			//增加天气预报_导航
			this.sql="insert into news_buttons (buttonname,buttontext,buttonicon,buttoncontenttype,buttontype,buttonaction) values (?,?,?,?,?,?)";
			Query	query=em.createNativeQuery(sql);
			
				query.setParameter(1, weatherButton.getButtonname());
				query.setParameter(2, weatherButton.getButtontext());
				query.setParameter(3, weatherButton.getButtonicon());
				query.setParameter(4, weatherButton.getButtoncontenttype());
				query.setParameter(5, weatherButton.getButtontype());
				query.setParameter(6, weatherButton.getButtonaction());
				query.executeUpdate();
			
			//增加天气预报_detail
			this.sql="insert into t_weatherdetail (province,weatherdate,weatherinfo,weatherindex,weathericon,updatetime) values (?,?,?,?,?,?)";
			query=em.createNativeQuery(sql);
			for(Weather weather_temp:weatherList){
				query.setParameter(1, weather_temp.getProvince());
				query.setParameter(2, weather_temp.getWeatherdate());
				query.setParameter(3, weather_temp.getWeatherinfo());
				query.setParameter(4, weather_temp.getWeatherindex());
				query.setParameter(5, weather_temp.getWeathericon());
				query.setParameter(6, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(weather_temp.getUpdatetime()));
				query.executeUpdate();
			}
		
		} catch (Exception e) {
			resultInt=-1;
			logger.info("addWeather fail !!!" + e.getMessage());
			e.printStackTrace();
			
		}
		return resultInt;
	}
	
	/**
	 * 更新天气预报
	 * @param hashMap weatherButton,weatherDetailList
	 * @return	int -2:记录存在;-1：失败;0:成功;
	 */
	public int updateWeather(DataMap hashMap){
		List<Weather> weatherList=(List<Weather>) hashMap.get("weatherList");
		NewsButtons weatherButton=(NewsButtons) hashMap.get("weatherButton");
		Weather weather=(Weather) hashMap.get("weather");
		int resultInt = 0;
		try {
			
			this.sql="SELECT count(*) FROM news_buttons WHERE buttonname='"+weatherButton.getButtonname()+"' AND buttontype=4 AND buttonid!="+weather.getButtonid();
			if(this.getOneInt()>0){
				return -2;
			}
			//更新天气预报_导航
			this.sql="update news_buttons set buttonname=?,buttontext=?,buttonicon=?,buttoncontenttype=?,buttontype=?,buttonaction=? " +
					" where buttonid=?";
			Query	query=em.createNativeQuery(sql);
			query.setParameter(1, weatherButton.getButtonname());
			query.setParameter(2, weatherButton.getButtontext());
			query.setParameter(3, weatherButton.getButtonicon());
			query.setParameter(4, weatherButton.getButtoncontenttype());
			query.setParameter(5, weatherButton.getButtontype());
			query.setParameter(6, 0);
			query.setParameter(7, weather.getButtonid());
			query.executeUpdate();
			
			//更新天气预报_detail
			this.sql="update t_weatherdetail set province=?,weatherdate=?,weatherinfo=?,weatherindex=?,weathericon=?,updatetime=?" +
					" where province=? and weatherdate=?";
			query=em.createNativeQuery(sql);
			for(Weather weather_temp:weatherList){
				query.setParameter(1, weather_temp.getProvince());
				query.setParameter(2, weather_temp.getWeatherdate());
				query.setParameter(3, weather_temp.getWeatherinfo());
				query.setParameter(4, weather_temp.getWeatherindex());
				query.setParameter(5, weather_temp.getWeathericon());
				query.setParameter(6, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(weather_temp.getUpdatetime()));
				query.setParameter(7, weather_temp.getProvince());
				query.setParameter(8, weather_temp.getWeatherdate());
				query.executeUpdate();
			}
			
		} catch (Exception e) {
			resultInt=-1;
			logger.info("updateWeather fail !!!" + e.getMessage());
			e.printStackTrace();
			
		
		}
		return resultInt;
	}
	
	/**
	 * 删除天气预报
	 * @param hashMap	city
	 * @return	int -1：失败;0:成功;
	 */
	public int delete_Weather(DataMap hashMap) {
		Integer buttonid=(Integer) hashMap.get("buttonid");
		int resultInt = 0;
		try {
			
			//删除天气预报_detail
			this.sql="delete from t_weatherdetail where province=(select nb.buttonname from  news_buttons nb where nb.buttontype=4 and nb.buttonid="+buttonid+")";
			this.em.createNativeQuery(sql).executeUpdate();
			
			//删除导航和频道对应关系
			this.sql="delete from news_extends_firstchannel_buttons where buttonid="+buttonid;
			this.em.createNativeQuery(sql).executeUpdate();
			
			//删除天气预报_导航
			this.sql="delete from news_buttons where buttonid="+buttonid;
			this.em.createNativeQuery(sql).executeUpdate();
		} catch (Exception e) {
			resultInt=-1;
			logger.info("delete_Weather fail !!!" + e.getMessage());
			e.printStackTrace();
		}
		return resultInt;
	}
	
	/**
	 * findObjectById
	 * @param id
	 * @return Object
	 */
	public Object findObjectById(Class c, Serializable id) {
		Object o = null;
		try {
			o = this.em.find(c, id);
		} catch (Exception e) {
			logger.error(e.getMessage());
			e.printStackTrace();
		}
		if (o == null) {
			String msg = "Uh oh, '" + c + "' object with id '" + id
					+ "' not found...";
			logger.warn(msg);
			throw new EntityNotFoundException(msg);
		}
	
		return  o;
	}
	
	/**
	 *  验证城市名称唯一
	 * @param city,city_old
	 * @return
	 */
	public int checkCity_unique(String city,String city_old) {
		int resultInt = 0;
		try {
			
			this.sql="SELECT count(*) FROM news_buttons WHERE buttonname='"+city+"' AND buttontype=4 ";
		
			if(this.getOneInt()>0){
				if(city_old!=null){
					if(!city_old.equals(city)){
						return 1;
					}else{
						return 0;
					}
				}
				return 1;
			}
		
		} catch (Exception e) {
			resultInt=-1;
			logger.info("checkGrouprulename_unique fail !!!" + e.getMessage());
			e.printStackTrace();
		
		}
		return resultInt;
	}

	
	
	//********************************************手动录入天气预报_End*********************************************************

	

	

	


}